#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.conf.urls import url
from django import forms

from stark.service.stark import StarkConfig, get_date_text, Option, Row
from stark.forms.forms import StarkModelForm

from django.forms import ModelForm
from teach import models


class TeachingDailyOption(Option):

    def get_queryset(self, _field, model_class, config):
        cls_id = config.kwargs.get('cls_id')
        course_id = config.kwargs.get('course_id')

        return Row(models.Module.objects.filter(course_id=course_id), self, config.request.GET)


class TeachingDailyModelForm(StarkModelForm):
    class Meta:
        model = models.TeachingDaily
        exclude = ['cls']
        widgets = {
            'module': forms.RadioSelect(),
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(request, *args, **kwargs)
        course_id = request.resolver_match.kwargs.get('course_id')
        for name, field in self.fields.items():
            if name == 'module':
                field.queryset = models.Module.objects.filter(course_id=course_id)
                field.empty_label = None
                field.widget.attrs['class'] = 'form-radio'


class TeachingDailyHandler(StarkConfig):
    """
    实际教学日管理
    """
    model_form_class = TeachingDailyModelForm

    list_display = ['title','module', 'teacher']

    list_edit = ['teacher']

    order_by = ['module_id', 'order']

    list_filter = [
        TeachingDailyOption('module')
    ]

    def get_urls(self):
        urlpatterns = [
            url(r'^list/(?P<cls_id>\d+)/(?P<course_id>\d+)/$', self.wrapper(self.changelist_view),
                name=self.get_list_url_name),
            url(r'^add/(?P<cls_id>\d+)/(?P<course_id>\d+)/$', self.wrapper(self.add_view), name=self.get_add_url_name),
            url(r'^(?P<pk>\d+)/change/(?P<cls_id>\d+)/(?P<course_id>\d+)/', self.wrapper(self.change_view),
                name=self.get_change_url_name),
            url(r'^(?P<pk>\d+)/del/(?P<cls_id>\d+)/(?P<course_id>\d+)/', self.wrapper(self.delete_view),
                name=self.get_del_url_name),
        ]
        return urlpatterns

    def get_queryset(self, *args, **kwargs):
        cls_id = kwargs.get('cls_id')
        course_id = kwargs.get('course_id')
        return models.TeachingDaily.objects.filter(cls_id=cls_id, cls__course_id=course_id)

    def save(self, form, modify=False):
        if not modify:
            form.instance.cls_id = self.kwargs.get('cls_id')
        form.save()